package com.evil.activiti.listener;

import com.alibaba.fastjson.JSON;
import com.evil.activiti.util.ActivityUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 流转线执行监听器
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Slf4j
@Component("FlowTakeListener")
@AllArgsConstructor
public class FlowTakeListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) {
        String eventName = execution.getEventName();
        Long orderId = execution.getVariable(ActivityUtil.getProcessOrderIdKey(), Long.class);
        FlowElement flowElement = execution.getCurrentFlowElement();
        Map<String, Object> variables = execution.getVariables();
        log.info("【流转线执行监听器】，execution.getEventName参数：{}", eventName);
        log.info("【流转线执行监听器】，订单id:{}", orderId);
        log.info("【流转线执行监听器】，节点id：{}, 节点name:{}", flowElement.getId(), flowElement.getName());
        log.info("【流转线执行监听器】，execution.getVariables参数：{}", JSON.toJSONString(variables));

        // 执行事件
        if (EVENTNAME_TAKE.equals(execution.getEventName())) {
            if (flowElement instanceof SequenceFlow) {
                SequenceFlow sequenceFlow = (SequenceFlow) flowElement;

                // 流程变量记录 来龙去脉
                Long sourceNodeId = ActivityUtil.restoreFlowNodeId(sequenceFlow.getSourceRef());
                Long targetNodeId = ActivityUtil.restoreFlowNodeId(sequenceFlow.getTargetRef());
                execution.setVariable(ActivityUtil.getSequenceFlowKey(targetNodeId), sourceNodeId);
            }
        }
    }
}
